package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：seanyang
 * @date ：Created in 2019/6/12
 * @description ：套餐Controller
 * @version: 1.0
 */
@RestController
@RequestMapping("/mobile/setmeal")
public class SetmealController {

	@Autowired
	private JedisPool jedisPool;

	@Reference
	private SetmealService setmealService;

	/**
	 * 获取套餐列表数据
	 * @return
	 */
	@RequestMapping("/getSetmeal")
	public Result getSetmeal(){
		ObjectMapper objectMapper = new ObjectMapper();
		List<Setmeal> list1=new ArrayList<>();
		String list2 = jedisPool.getResource().get("list");

		try{
			if(list2!=null){
//                如果有就取
				List readValue = objectMapper.readValue(list2, List.class);
				return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,readValue);
			}else{
//                如果没有就调用方法
				List<Setmeal> all = setmealService.findAll();
				list2 = objectMapper.writeValueAsString(all);
				jedisPool.getResource().setex("list",5*60,list2);
				return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,all);

			}
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false,MessageConst.QUERY_SETMEAL_FAIL);
		}
	}

	@RequestMapping("/findById")
	public Result findById(Integer id){
		ObjectMapper objectMapper = new ObjectMapper();
		String setmeal1 = jedisPool.getResource().get("setmeal");
		try{
			if(setmeal1!=null){
				Setmeal setmeal = objectMapper.readValue(setmeal1, Setmeal.class);
				return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
			}else{
				Setmeal setmeal = setmealService.findById(id);
				String s = objectMapper.writeValueAsString(setmeal);
				jedisPool.getResource().setex("setmeal",5*60,s);
				return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
			}
		}catch(Exception e){
		    e.printStackTrace();
		    return new Result(false,MessageConst.QUERY_SETMEAL_FAIL);
		}
	}


}
